package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpExprService empExprService;

   /* @Override
    public PageResult<Emp> page(EmpQueryParam param) {
        log.info("员工列表查询条件：{}", param);
        // 设置分页参数
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        //构建查询条件
        //如果参数name有值，就进行模糊查询
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(StringUtils.hasLength(param.getName()), Emp::getName, param.getName());
                queryWrapper.eq(null != param.getGender(), Emp::getGender, param.getGender());
                queryWrapper.gt(null != param.getBegin(), Emp::getEntryDate, param.getBegin());
                queryWrapper.lt(null != param.getEnd(), Emp::getEntryDate, param.getEnd());
        // 分页查询;
        page(page, queryWrapper);
        *//*Page<Emp> pageInfo = getBaseMapper().selectPage(page, queryWrapper);
        System.out.println("pageInfo==page = " + (pageInfo == page));
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getRecords());*//*
        return new PageResult<>(page.getTotal(),page.getRecords());
    }*/

    @Override
    public PageResult<Emp> page(EmpQueryParam param) {
        log.info("员工列表查询条件：{}", param);
        // 设置分页参数
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        //构建查询条件
        //如果参数name有值，就进行模糊查询
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(param.getName()), Emp::getName, param.getName());
        queryWrapper.eq(null != param.getGender(), Emp::getGender, param.getGender());
        queryWrapper.gt(null != param.getBegin(), Emp::getEntryDate, param.getBegin());
        queryWrapper.lt(null != param.getEnd(), Emp::getEntryDate, param.getEnd());
        // 分页查询;
        page(page, queryWrapper);


        //补全部门名称
        List<Emp> empList = page.getRecords();
        /*Set<Integer> deptIds = new HashSet<>();
        for (Emp emp : empList) {
            deptIds.add(emp.getDeptId());
        }*/
        Set<Integer> deptIds = empList.stream().map(Emp::getDeptId).collect(Collectors.toSet());

        // 获取部门id集合
        List<Dept> depts = deptMapper.selectBatchIds(deptIds);
        Map<Integer, String> deptMap = depts.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
        // 给每个员工设置部门名称
        empList.forEach(e -> { //100
            Integer deptId = e.getDeptId();
            //Dept dept = depts.stream().filter(d->d.getId().equals(deptId)).findAny().get(); //20
            String deptName = deptMap.get(deptId); //map<key=id,value=name>
            e.setDeptName(deptName);
        });


        /*empList.forEach(e->{
            Integer deptId = e.getDeptId();
            Dept dept = deptMapper.selectById(deptId);// 发送查询语句，改成批量查询
            if(null != dept){
                e.setDeptName(dept.getName());
            }
        });*/

        return new PageResult<>(page.getTotal(), empList);
    }

    @Override
    @Transactional
    public void updateEmp(Emp emp) {
        /*lambdaUpdate().set(StringUtils.hasLength(emp.getPassword()), Emp::getPassword, emp.getPassword())
                .set(StringUtils.hasLength(emp.getName()), Emp::getName, emp.getName())
                .set(null != emp.getGender(), Emp::getGender, emp.getGender())
                .set(null != emp.getJob(), Emp::getJob, emp.getJob())
                .set(null != emp.getEntryDate(), Emp::getEntryDate, emp.getEntryDate())
                .set(null != emp.getDeptId(), Emp::getDeptId, emp.getDeptId())
                .set(null != emp.getSalary(), Emp::getSalary, emp.getSalary())
                .set(StringUtils.hasLength(emp.getPhone()), Emp::getPhone, emp.getPhone())
                .set(StringUtils.hasLength(emp.getImage()), Emp::getImage, emp.getImage())
                .eq(Emp::getId, emp.getId())
                .update();*/
        // 如果字段的值为null则不参与更新
        updateById(emp);
        //删除旧的工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        //添加新的工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            //设置员工id
            exprList.forEach(e->e.setEmpId(emp.getId()));
            empExprService.saveBatch(exprList);
        }

    }

    /**
     * 添加员工
     * @param emp
     */
    @Transactional
    @Override
    public void saveEmp(Emp emp) {
        //1、保存员工信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(emp.getCreateTime());
        save(emp);
        log.info("新增员工的id:{}", emp.getId());
        //2、添加工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            //设置员工的id
            exprList.forEach(er->er.setEmpId(emp.getId()));
            //批量保存工作经历
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    public Emp getInfoById(Integer id) {

        // 查询员工信息
        Emp emp = getById(id); // 查询数据库 1
        // 查询部门信息
        CompletableFuture<Dept> deptCompletableFuture = CompletableFuture.supplyAsync(() -> deptMapper.selectById(emp.getDeptId()));
        deptCompletableFuture.whenComplete((dept, throwable) -> Optional.of(dept).ifPresent(d->emp.setDeptName(d.getName())));
        CompletableFuture<List<EmpExpr>> listCompletableFuture = CompletableFuture.supplyAsync(() -> empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id)));
        listCompletableFuture.whenComplete((exprList, throwable) -> Optional.of(exprList).ifPresent(e->emp.setExprList(e)));
        CompletableFuture.allOf(deptCompletableFuture,listCompletableFuture);

        return emp;
    }

    @Override
    @Transactional
    public void deleteByIds(List<Integer> ids) {
        if(!CollectionUtils.isEmpty(ids)) {
            //先删除 员工数据
            removeBatchByIds(ids);
            //再删除工作经历
            empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
        }
    }

}
